<template>
    <div>
      <table-expand
        ref="table"
        :columns="columns"
        :data="data"
        :loading="loading"
        :config="config"
        :pageSizeOpts="pageSizeOpts"
        :pageNavigation="pageNavigation"
        :queryFormItem="queryFormItem"
        :collapseFormItem="collapseFormItem"
        :additionalAction="additionalAction"
        :pageAdditionalAction="pageAdditionalAction"
        @loadPage="loadPage"
        @handleCreate="handleCreate"
        @handleDetail="handleDetail"
        @handleEdit="handleEdit"
        @handleDelete="handleDelete"
        @handleDeleteMultiple="handleDeleteMultiple"
        @handleSearch="handleSearch"
        @handleReset="handleReset"
        @getSelection="getSelection"
      ></table-expand>
      <newDynamicModal
        ref="addModal"
        v-bind="addNewPanel"
        :modelType="modelType"
        :columns="formColumns"
        :rules="rules"
        @submit="handleNewAddSubmit"
      ></newDynamicModal>
      <edit-modal
        v-bind="editPanel"
        :modelType="modelType"
        :columns="formColumns"
        :rules="rules"
        @submit="handleEditSubmit"
      ></edit-modal>
      <read-modal
        v-bind="readPanel"
        :modelType="modelType"
        :columns="columns"
        :rules="rules"
      ></read-modal>
      <!-- 绑定工艺参数 -->
        <select-modal-opt
        v-bind="paramSelectPanel"
        :modelType="paramSelectModelType"
        :type="paramSelectType"
        :className="paramSelectClassName"
        :columns="paramSelectColumns"
        :moreColumn="paramSelectMormColumns"
        :formColumns="paramSelectFormColumns"
        :isSingleCheck="isSingleCheck"
        :selectionData="paramsSelectionData"
        @submit="handleParamSelectSubmit"
        ></select-modal-opt>
      <!-- 修改执行结果 -->
      <single-modal v-bind="resultPanel" :title="'edit'" @submit="handleResultSubmit">
        <formRule ref="_formRule" :data="resultData" :cols="resultPanel.cols" :columns="resultColumns"></formRule>
      </single-modal>
      <createQrCode ref="createQrCode" :qrContentKeys="qrContentKeys"></createQrCode>
    </div>
</template>

  <script>
    import newDynamicModal from '@/pages/components/newDynamicModal.vue';
    import editModal from '@/pages/components/editModal.vue';
    import readModal from '@/pages/components/readModal.vue';
    import createQrCode from '@/pages/components/createQrCode';
    import { typeClassName } from '@/pages/config/classNameMap';
    import mixin from '@/pages/components/mixins/mixin'
    import actionConditonMixin from '../mixins/actionConditonMixin'
    import recordEquipParamsMixin from '../mixins/recordEquipParamsMixin'
    import columnsMixin from './config'
    import selectModalOpt from '@/pages/components/selectModalOpt.vue';
    import singleModal from '@/pages/components/singleModal.vue';
    import formRule from '@/pages/components/formRule';
    import tableExpand from '@/pages/components/tableExpand.vue';
    export default {
        components: { newDynamicModal, editModal, readModal, selectModalOpt, singleModal, formRule, tableExpand,createQrCode },
        name: 'equipment',
        mixins: [mixin, actionConditonMixin, recordEquipParamsMixin,columnsMixin],
        data () {
            return {
                classObject: null, // 单个实例
                collectionObject: null, // 所有实例
                className: typeClassName['equipment'].className,
                type: typeClassName['equipment'].type,
                modelType: typeClassName['equipment'].modelType,
                isSingleCheck: false,
                // 绑定工艺参数
                paramSelectClassName: typeClassName['equipTechnologyParam'].className,
                paramSelectType: typeClassName['equipTechnologyParam'].type,
                paramSelectModelType: typeClassName['equipTechnologyParam'].modelType,
                paramsSelectionData: [], // 工艺参数
                hierOptions: [], // 仓库、库位数据
                locationOptions: [], // 联动库位
                addNewPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2,
                    data:{}
                },
                editPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2,
                    data: {}
                },
                readPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2,
                    data: {}
                },
                paramSelectPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2,
                    data: {}
                },
                bindParams: [], // 已绑定工艺参数项
                resultData: {}, // 绑定参数值
                resultColumns: [],
                resultPanel: {
                    width: 1024,
                    zIndex: 100,
                    titleStyle: {},
                    drawer: {
                        show: false
                    },
                    cols: 2
                },
                rules: {
                    sf_code: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_name: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    sf_equipmentType: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    equipmentPower: [
                        { required: true, type: 'number', message: '不能为空', trigger: 'blur' }
                    ],
                    sf_store: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    emptyLocation: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    fillLocation: [
                        { required: true,type:'array', message: '不能为空', trigger: 'blur' }
                    ],
                    downLocation: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    downFillLocation: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    workshop: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    // sf_workshopSection: [
                    //     { required: true, message: '不能为空', trigger: 'blur' }
                    // ]
                },
                loading: false,
                config: {
                    search: true,
                    addButton: true,
                    batchDeleteButton: true,
                    tableSizeIcon: true,
                    fullscreenIcon: true,
                    refreshIcon: false,
                    columnSettingIcon: true,
                    action: true,
                    additionalAction: true,
                    pageAdditionalAction: true
                },
                pageSizeOpts: [10, 30, 50, 100],
                pageNavigation: { total: 0, pageSize: 10, pageNumber: 1 },
                equipTypeClassObject: null,
                equipTypeOptions: [], // 类别名称选项
                // 进入页面需要的筛选条件：所属分类，'0'设备和'1'仪表
                selfFilter: { 'sf_category': '0' },
                // 新增数据需要添加的默认数据：所属分类，'0'设备和'1'仪表
                defaultAddData: { 'sf_category': '0','sf_status':'启用' },
                tableSelection:[],
                qrContentKeys:['sf_name','id','sf_code'],  //二维码中包含的字段
                energyShowOptions: [{label: '是', value: true}, {label: '否', value: false}]
            };
        },
        computed: {
            filterEquipTypeOptions () {
                return this.equipTypeOptions.filter(d => d.category === '0')
            },
            additionalAction () {
                let additionalAction = {
                    key: 'additionalAction',
                    title: {
                        'zh-CN': '附加操作',
                        'en-US': 'additional action'
                    }[this.G_Locale],
                    slot: 'additionalAction',
                    width: 200,
                    fixed: 'right',
                    align: 'center',
                    show: true,
                    buttons: [
                        { title: {
                              'zh-CN': '绑定工艺参数',
                              'en-US': 'bindTechnologyParam'
                          }[this.G_Locale],
                          event: (row, index) => this.handleParam(row, index)
                        },
                        { title: {
                              'zh-CN': '修改工艺参数',
                              'en-US': 'updateTechnologyParam'
                          }[this.G_Locale],
                          event: (row, index) => this.updateParam(row, index)
                        }
                    ]
                }
                this.G_IsMobile && (additionalAction.width = 90)
                return additionalAction
            },
            pageAdditionalAction () {
                return {
                    width: 200,
                    align: 'center',
                    buttons: [
                        { title: {
                              'zh-CN': '生成二维码',
                              'en-US': 'qrcode'
                          }[this.G_Locale],
                          event: () => this.getQrCode()
                        }
                    ]
                }
            },
            data () {
                if (this.collectionObject) {
                    return this.collectionObject.records.map(d => {
                        return {
                            ...d,
                            ...d.values
                        }
                    })
                } else {
                    return [];
                }
            },
            // 仓库
            storeOptions(){
                return this.hierOptions.filter(item => item.parentId === 'root')
            },
            // 所有库位
            allWarehouseOptions(){
                return this.hierOptions.filter(item => item.parentId !== 'root')
            }
        },
        beforeMount () {
            this.collectionObject = this.$modelObject.create(`${this.modelType}Collection`);
            this.classObject = this.$modelObject.create(this.modelType);
            this.equipTypeClassObject = this.$modelObject.create(typeClassName['equipType'].modelType);
            this.setOptionsByHier('equipType', this.equipTypeClassObject, 'equipTypeOptions', {
                label: 'sf_name', value: 'sf_code', category: 'category'
            })
            this.loadPage(this.pageNavigation, null);
            this.getAllStoreOptions('storehouseConfig', this.$modelObject.create(`${typeClassName['storehouseConfig'].modelType}`), 'hierOptions')
        },
        watch:{
            'addNewPanel.drawer.show': function (show) {
                if (show) {
                    this.addNewPanel.data = this.$modelObject.getTpl(this.modelType);
                }
            },
            'addNewPanel.data.values': {
                handler (values) {
                    this.locationOptions = this.allWarehouseOptions.filter(d=>d.parentId===values.sf_store)
                },
                deep: true
            },
            'editPanel.data.values': {
                handler (values) {
                    this.locationOptions = this.allWarehouseOptions.filter(d=>d.parentId===values.sf_store)
                },
                deep: true
            }
        },
        methods: {
            // 绑定工艺参数
            async handleParam (row) {
                this.loading = true;
                if (await this.getRecord({ type: row.type, className: row.className, id: row.id })) {
                    this.paramsSelectionData = this.getSelectionByHierClassName(typeClassName['equipTechnologyParam'].className)
                    this.$set(this.paramSelectPanel.drawer, 'show', true)
                    this.loading = false;
                } else {
                    this.loading = false;
                }
            },
            // 绑定工艺参数确定操作
            handleParamSelectSubmit (selection) {
                let pointer = { className: this.className, type: this.type, id: this.classObject.record.id }
                let newData = selection.map(d => {
                    return {
                        values: { sf_name: d.label, id: d.id },
                        name: 'equipTechnologyParam-' + String(d.id),
                        id: d.id,
                        model: typeClassName['equipTechnologyParam'].modelType,
                        pointer: { id: d.id, className: typeClassName['equipTechnologyParam'].className, type: typeClassName['equipTechnologyParam'].type }
                    }
                })
                let originalData = [];
                if (!!this.classObject.hier && this.classObject.hier.length > 0) {
                    this.classObject.hier[0].basic.forEach(item => {
                        if (item.pointer.className !== typeClassName['equipTechnologyParam'].className) {
                            originalData.push({ ...item })
                        }
                    })
                }
                newData = [...newData, ...originalData]
                // 添加hier中某项的接口
                this.hierAllAddRegister(pointer, newData, this.paramSelectPanel)
            },
            // 修改工艺参数值弹框
            updateParam (row) {
                this.getRecord({ type: row.type, className: row.className, id: row.id }).then(flag => {
                    if (flag) {
                        this.resultData = this.classObject.record.values.paramValue||{};
                        this.$set(this.resultPanel.drawer, 'show', true)
                        if (this.classObject.isValidHier()) {
                            this.bindParams = this.classObject.hier[0].basic.filter(d => d.pointer.className === this.paramSelectClassName)
                            // 获取已绑定工艺参数项
                            this.getTechnologyParamData()
                        }
                    }
                })
            },
            // 获取已绑定工艺参数项
            getTechnologyParamData () {
                let paramCollectionObject = this.$modelObject.create(`${this.paramSelectModelType}Collection`)
                let filter = {
                    className: this.paramSelectClassName,
                    type: this.paramSelectType
                }
                let newFilter = '';
                if (this.tools.isReal(filter)) {
                    newFilter = paramCollectionObject.util.getFilter(filter);
                }
                paramCollectionObject.query(newFilter).then(flag => {
                    if (flag) {
                        let ids = this.bindParams.map(d => String(d.id))
                        let data = paramCollectionObject.filterRecordsByHierIds(ids)
                        let resultColumns = data.map(d => {
                            let column = {
                                ...this.commonColumnConfig,
                                key: d.values['sf_code'],
                                title: {
                                    'zh-CN': d.values['sf_name'],
                                    'en-US': d.values['sf_code']
                                }[this.G_Locale],
                                config: this.getColumnType(d.values.itemType, d.hier)
                            }
                            if (d.values.itemType === '多选') {
                                column.rule = { required: true, type: 'array', message: '不能为空', trigger: 'change' }
                            }
                            return column;
                        })
                        this.resultColumns = resultColumns
                    } else {
                        this.resultColumns = []
                    }
                })
            },
            // 修改工艺结果保存
            handleResultSubmit () {
                this.$refs._formRule.$refs.form.validate(valid => {
                    if (valid) {
                        this.classObject.record.values.paramValue = this.resultData
                        this.classObject.update().then((flag) => {
                            if (flag) {
                                let index = this.collectionObject.records.findIndex(
                                    (item) => item.id === this.classObject.record.id
                                );
                                if (index !== -1) {
                                    this.collectionObject.records.splice(
                                        index,
                                        1,
                                        this.classObject.record
                                    );
                                }
                                this.$set(this.resultPanel.drawer, 'show', false);
                            }
                        });
                    }
                });
            },
            getSelection(selection){
                this.tableSelection = selection;
            },
            getQrCode(){
                this.$refs.createQrCode.printQrCode(this.tableSelection)
            },
            // 拿到仓库/库位所有数据
            getAllStoreOptions (classMapName, classObject, optionName) {
              let filter = {
                  className: typeClassName[classMapName].className,
                  type: typeClassName[classMapName].type
              }
              let newFilter = '';
              if (this.tools.isReal(filter)) {
                  newFilter = classObject.util.getFilter(filter);
              }
              let options = []
              return classObject
                  .query(newFilter)
                  .then((flag) => {
                      if (flag && classObject.isValidHier()) {
                          options = classObject.record.hier[0].basic.map(d => {
                              return {
                                label: d.title === null ? '' : d.title,
                                value: d.id === null ? '' : d.id,
                                parentId: d.parentId === null ? '' : d.parentId
                              }
                          })
                      } else {
                          options = [];
                      }
                      this[optionName] = options
              });
            },
            // 查看框显示
            readDataCondition(data) {
              data.sf_store = this.getOptionValue(this.storeOptions, data.sf_store)
              data.emptyLocation = this.getOptionValue(this.allWarehouseOptions, data.emptyLocation)
              data.fillLocation = this.getOptionValue(this.allWarehouseOptions, data.fillLocation)
              data.downLocation = this.getOptionValue(this.allWarehouseOptions, data.downLocation)
              data.downFillLocation = this.getOptionValue(this.allWarehouseOptions, data.downFillLocation)
            },
        }
    };
  </script>
  <style scoped lang="scss"></style>
